import Vue from 'vue'
import VueRouter from 'vue-router'
import login from '../views/login.vue'
import home from '../views/home.vue'
import { userSetter } from 'core-js/fn/symbol'
Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: login
  },{
    path:"/",
    name:'home',
    component:home,
    children: [
      {
        path: '/users',
        name:userSetter,
        component: () => import(/* webpackChunkName: "login" */ '../views/users.vue')
      },
      
    ]
  }
]

const router = new VueRouter({
  routes
})
//因为再早的生命周期函数Vue实例都会创建完毕,
//因此用生命周期函数进行检测token如果尚未登录则会造成不必要的报错(比如找不到本地缓存的参数)
//最好的办法就是在进行路由导航时在实例未初始化时候使用导航守卫进行检测,防患于未然
router.beforeEach((to, from, next) => {
  // console.log(localStorage.getItem('userinfo')? true:false);
  if(to.path !== '/login'){
      // console.log('执行了外层');
    if(!localStorage.getItem('userinfo')){
      // console.log('执行了里层');
        next('/login')
    }
  }else if(to.path === '/login'){
    if(localStorage.getItem('userinfo')){
      // console.log('执行了里层');
        next('/')
    }
  }
  next()
})

export default router
